using System.Collections;
using UnityEngine;
using DG.Tweening;

public class DragObjectByMouse : MonoBehaviour
{
    private Vector3 _originPosition;
    private Quaternion _originRotation;
    private Tweener _tweener;
    readonly float Scale = 1f;
    
    void Start()
    {
        var transform1 = transform;
        _originPosition = transform1.localPosition;
        _originRotation = transform1.localRotation;
        
        _tweener = transform.DOLocalRotate(Vector3.up * 360, 4, RotateMode.LocalAxisAdd).SetEase(Ease.Linear).SetLoops(-1);
        //原地360度匀速旋转
        _tweener.Pause();//动画关闭
    }
    private IEnumerator OnMouseDown()
    {
        GameManager.m_Instance.m_ChooseState = EChooseState.Scale;
        var position = transform.position;
        if (Camera.main != null)
        {
            var screenSpace = Camera.main.WorldToScreenPoint(position);//射线检测物体
            var offset = position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));
            _tweener.Play();//动画开始
            while (Input.GetMouseButton(0))
            {
                if (Input.GetAxis("Mouse ScrollWheel") > 0)
                {
                    transform.DOScale(new Vector3(1, 1, 1), Scale);
                }
                else if (Input.GetAxis("Mouse ScrollWheel") < 0)
                {
                    transform.DOScale(new Vector3(4, 4, 4), Scale);
                }
                var curScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
                var curPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + offset;
                transform.position = curPosition;
          
                yield return new WaitForFixedUpdate();
            }
        }
    }
    private void OnMouseUp()
    {
        GameManager.m_Instance.m_ChooseState = EChooseState.None;
        _tweener.Pause();//若动画停止

        var transform1 = transform;
        transform1.localPosition = _originPosition;//得到拾取对象的坐标
        transform1.localRotation = _originRotation;//拾起的物体回归原位置
        transform.DOScale(new Vector3(1, 1, 1), Scale);//物体大小归至2*2*2
       
    }
}
